<?php
/**
 * Created by PhpStorm.
 * User: hexvliang
 * Date: 2015/11/5
 * Time: 11:53
 */

namespace Common\Model;

use Think\Model;

/**
 * 事件记录对应的表
 * Class TimingEventsModel
 * @package Common\Model
 */
class TimingEventsModel extends Model
{
    protected $tableName = 'timing_events';

    /**
     * 添加事件记录
     * @param string $name
     * @param string $functionUrl
     * @param array|null $parameters
     * @param bool|false $isCycle
     * @param int $cycleSecond
     * @return bool|mixed
     */
    public static function addEvent($name, $functionUrl, $parameters = null, $isCycle = false, $cycleSecond = 0)
    {
        if (empty($name) || empty($functionUrl)) {
            return false;
        }
        if (!empty($parameters) && !is_array($parameters)) {
            return false;
        }
        if (!is_bool($isCycle)) {
            return false;
        }
        if (!is_numeric($cycleSecond)) {
            return false;
        }

        //周期性事件至少时间是5秒
        if ($isCycle === true && (int)$cycleSecond <= 1) {
            $cycleSecond = 5;
        }

        $data['name'] = trim($name);
        $data['api_address'] = trim($functionUrl);
        $data['api_parameters'] = empty($parameters) ? null : serialize($parameters);
        $data['is_cycle'] = $isCycle;
        $data['cycle_second'] = $cycleSecond;
        $data['creat_time'] = date('Y-m-d H:i:s', time());
        $m = D('Common/TimingEvents');
        return $m->add($data);
    }

    /**
     * 通过名字查询事件
     * @param $name
     * @return bool|mixed
     */
    public static function getEventByName($name)
    {
        if (empty($name)) {
            return false;
        }
        $m = D('Common/TimingEvents');
        return $m->where(array('name' => $name))->find();
    }

    /**
     * 删除数据库中的事件记录
     * @param $name
     * @return bool|mixed
     */
    public static function deleteEventByName($name)
    {
        if (empty($name)) {
            return false;
        }
        $m = D('Common/TimingEvents');
        return $m->where(array('name' => trim($name)))->delete();
    }

}